package restaurant.behaviours.master;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.ListIterator;

import restaurant.agents.MasterWaiterAgent;
import restaurant.core.CustomizedPerformative;

public class MasterCallChoiceBehaviour extends CyclicBehaviour {
	
	private static final long serialVersionUID = -2204214886040496210L;
	private MasterWaiterAgent agent;
	
	public MasterCallChoiceBehaviour(MasterWaiterAgent agent) {
		this.agent = agent;
	}

	@Override
	public void action() {
		if(this.agent.restaurant.calls == null || this.agent.restaurant.calls.isEmpty())
			return;
		
		if(this.agent.freeWaiters.isEmpty())
			return;
		
		synchronized (this.agent.restaurant.calls) {
			ListIterator<Hashtable<Integer, Boolean>> iterator = this.agent.restaurant.calls.listIterator();
			while(iterator.hasNext()) {
				Hashtable<Integer, Boolean> hashtable = iterator.next();
				int t = hashtable.keys().nextElement();
				if(!hashtable.get(t)) {
					for(int i = 0; i < this.agent.freeWaiters.keySet().size(); i++) {
//					for (Iterator<AID> waiter = this.agent.freeWaiters.keySet().iterator(); waiter.hasNext();) {
//						AID tmp = waiter.next();
						List<AID> tmpList = new ArrayList<AID>();
						for (Object aid : this.agent.freeWaiters.keySet().toArray()) {
							tmpList.add((AID) aid);
						}
						Collections.shuffle(tmpList);
						AID tmp = tmpList.get(i);
						if(this.agent.freeWaiters.get(tmp)) {
							this.agent.setScore(this.agent.getScore() + (1000/(System.currentTimeMillis() + 1 - this.agent.calledTime.get(t))));
							
							hashtable.put(t, true);
							this.agent.freeWaiters.put(tmp, false);
							ACLMessage message = new ACLMessage(CustomizedPerformative.AVAILABLE_WAITER);
							message.setContent("" + CustomizedPerformative.WAITER_CALLING);
							message.addReceiver(tmp);

							System.out.println("MasterWaiterAgent: Un cliente vuole ordinare");
					
							myAgent.send(message);
							return;
						}
					}
				}
			}
		}
	}

}